import React, { useEffect, useState, useMemo } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

let map;
let _AMap;
let cleanState = false;
const Map = () => {
  const [, setMarkers] = useState([]);
  const [inputValue, setInputValue] = useState('');

  let lines = useMemo(() => [], []);
  let textArr = useMemo(() => [], []);

  useEffect(() => {
    AMapLoader.load({
      key: 'b0a56e953ee8b514b232380406c2baca', // 需要设置您申请的key

      version: '2.0',

      plugins: [
        'AMap.ToolBar',
        'AMap.Driving',
        'AMap.GraspRoad',
        'AMap.MouseTool',
        'AMap.RangingTool',
        'AMap.LngLat',
      ],

      AMapUI: {
        version: '1.1',

        plugins: [],
      },

      Loca: {
        version: '2.0.0',
      },
    }).then((AMap) => {
      _AMap = AMap;
      map = new AMap.Map('mapContains', {
        viewMode: '2D',
        zoom: 12, // 地图缩放级别,初始化的时候
        zooms: [10, 22], // 地图缩放级别范围 最小 10,最大22,如果比最小还小就是最小值(10)
        resizeEnable: true, // 是否监控地图容器尺寸变化
      });
      const mouseTool = new AMap.MouseTool(map);

      draw('marker', mouseTool, AMap);

      mouseTool.on('draw', (e) => drawMarkPolyline(e, AMap));
    });
  }, []);

  function draw(type, mouseTool, AMap) {
    switch (type) {
      case 'marker': {
        mouseTool.marker({
          // 同Marker的Option设置
          icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          offset: new AMap.Pixel(-13, -30),
        });

        break;
      }
      default:
        break;
    }
  }
  const drawMarkPolyline = (e, AMap) => {
    setMarkers((origin) => {
      if (cleanState) {
        map.add(origin);
      }
      const markers = [...origin, e.obj];
      renderLine(markers, AMap);
      setInputValue(transformationM_S(markers));
      cleanState = false;
      return markers;
    });
  };

  const renderLine = (markers, AMap) => {
    map.remove(lines);
    map.remove(textArr);
    lines = [];
    textArr = [];
    for (let i = 0; i < markers.length - 1; i++) {
      const j = i + 1;
      const p1 = markers[i].getPosition();
      const p2 = markers[j].getPosition();
      const oldLine = new AMap.Polyline({
        path: [
          [p1.KL, p1.kT],
          [p2.KL, p2.kT],
        ],
        strokeWeight: 8,
        strokeOpacity: 1,
        strokeColor: 'red',
      });
      map.add(oldLine);
      lines.push(oldLine);

      const text = new AMap.Text({
        text: '',
        style: {
          'background-color': '#29b6f6',
          'border-color': '#e1f5fe',
          'font-size': '12px',
        },
      });

      text.setMap(map);
      const textPos = p1.divideBy(2).add(p2.divideBy(2));
      const distance = Math.round(p1.distance(p2));
      text.setText('两点相距' + distance + '米');
      text.setPosition(textPos);
      textArr.push(text);
    }
  };

  const inputChange = (e) => {
    const value = e.target.value;
    setInputValue(value);
    // if (!value) {
    //   setMarkers([]);
    // }
  };

  function transformationM_S(arr) {
    return arr
      .map((item) => {
        return `${item.getPosition().lng},${item.getPosition().lat}`;
      })
      .join('\n');
  }

  const clean = () => {
    cleanState = true;
    map.clearMap();
  };

  const renderTrajectory = () => {
    clean();

    const markers = _.compact(inputValue.split('\n')).map((item) => {
      return new _AMap.Marker({
        icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        offset: new _AMap.Pixel(-13, -30),
        position: new _AMap.LngLat(item.split(',')[0], item.split(',')[1]),
      });
    });
    map.add(markers);
    setMarkers(markers);
    renderLine(markers, _AMap);
  };

  return (
    <>
      <div id="mapContains" style={{ width: '100%', height: '100%' }}></div>

      <textarea rows="10" value={inputValue} onChange={inputChange}></textarea>
      <button id="xrgj" onClick={renderTrajectory}>
        渲染轨迹
      </button>
      <button id="clearMap" onClick={clean}>
        清空画布
      </button>
    </>
  );
};

export default Map;
